﻿using System;
using System.ComponentModel;
using System.Drawing;

using Spencen.Mobile.UI.Layout;

namespace Spencen.Mobile.UI.Primitives
{
    public abstract class DrawingContainer : RectangleElement, ISupportInitialize
    {
        private LayoutEngine _layoutEngine;
        protected bool IsInitializing { get; set; }

        public DrawingContainer( IDrawingHost host )
        {
            IsInitializing = true;
            Children = new DrawingElementCollection( this );
            Children.CollectionChanged += new EventHandler( Children_CollectionChanged );
            Host = host;
            HitTestOnChildren = true;
            LayoutEngine = new StretchLayout();
            IsInitializing = false;
        }

        public DrawingElementCollection Children { get; private set; }
        public bool HitTestOnChildren { get; protected set; }
        public bool HitTestOnContainer { get; set; }

        public LayoutEngine LayoutEngine
        {
            get { return _layoutEngine; }
            set
            {
                if ( _layoutEngine != value )
                {
                    _layoutEngine = value;
                    LayoutChildren();
                    Invalidate();
                }
            }
        }

        protected override void OnRender( GraphicsContext context )
        {
            base.OnRender( context );

            foreach ( var childElement in Children )
            {
                var childContext = new GraphicsContext( context, childElement );
                childElement.Render( childContext );
            }
        }

        public override bool HitTest( Point hitPoint, GraphicsContext context )
        {
            //var panelContext = new GraphicsContext( (Graphics)null, this );
            //var child = Children.HitTest( hitPoint, panelContext );
            //return child != null;

            return HitTestOnContainer && base.HitTest( hitPoint, context );
        }

        protected override void OnResize()
        {
            base.OnResize();
            LayoutChildren();
        }

        protected virtual void LayoutChildren()
        {
            if ( LayoutEngine != null && !IsInitializing )
                LayoutEngine.LayoutChildren( Children, Size );
        }

        private void Children_CollectionChanged( object sender, EventArgs e )
        {
            LayoutChildren();
        }

        #region ISupportInitialize Members

        public virtual void BeginInit()
        {
            IsInitializing = true;
        }

        public virtual void EndInit()
        {
            IsInitializing = false;
            LayoutChildren();
        }

        #endregion
    }
}
